<?php 
namespace app\dboard\logic;
use think\Db;
use think\facade\Session;
class Course extends Base
{

	function __construct()
	{
	}

	public function create($param)
	{
		$sid = isset($param['sid']) ? intval($param['sid']):0;
		$name = isset($param['name']) ? trim($param['name']):'';
        $summary = isset($param['summary']) ? trim($param['summary']):'';
        $week = isset($param['week']) ? trim($param['week']):'';
        $start_time = isset($param['start_time']) ? trim($param['start_time']):'';
        $end_time = isset($param['end_time']) ? trim($param['end_time']):'';
        $classes_id = isset($param['classes_id']) ? trim($param['classes_id']):0;
        $classroom_id = isset($param['classroom_id']) ? trim($param['classroom_id']):0;
        $periods = isset($param['periods']) ? trim($param['periods']):'';
		$address = isset($param['address']) ? trim($param['address']):'';
		$pic = isset($param['pic']) ? trim($param['pic']):'';
		$ordernum = isset($param['ordernum']) ? intval($param['ordernum']):0;
		$isindex = isset($param['isindex']) ? intval($param['isindex']):0;
		$description = isset($param['description']) ? trim($param['description']):'';
        if (!$sid || !$name || !$summary || !$week || !$start_time || !$end_time || !$classes_id || !$classroom_id || !$periods || !$address) {
          $this->res_data['Msg'] = "缺少必填信息";
          return $this->res_data;
        }
		$store= Db::name('store')->where([['id','=',$sid]])->find();
		if (!$store) {
			$this->res_data['Msg'] = "无此门店";
			return $this->res_data;
		}
        $classes = Db::name('classes')->field('name,master_teacher')->where(['id'=>$classes_id])->find();
        if (!$classes) {
            $this->res_data['Msg'] = "课程班级参数有误";
            return $this->res_data;
        }
        $classes_name = $classes['name'];
        $teacher_id = $classes['master_teacher'];
        $teacher_name = Db::name('teacher')->where('id',$teacher_id)->value('name');
        $classroom_name = Db::name('classroom')->where(['id'=>$classroom_id])->value('name');
        if (!$classroom_name) {
            $this->res_data['Msg'] = "课程教室参数有误";
            return $this->res_data;
        }
        $week = trim($week,'|');
        $start_time = trim($start_time,'|');
        $end_time = trim($end_time,'|');
        $week_arr = explode('|', $week);
        $start_time_arr = explode('|', $start_time);
        $end_time_arr = explode('|', $end_time);
        if (count($end_time_arr)!=count($week_arr) || count($start_time_arr)!=count($week_arr)) {
            $this->res_data['Msg'] = "课程时间参数有误";
            return $this->res_data;
        }
        $class_time = '';
        foreach ($week_arr as $key => $value) {
            if ($key>0) {
                $class_time .= '|';
            }
            $class_time .= $value.','.$start_time_arr[$key].','.$end_time_arr[$key];
        }
        $data['sid'] =$sid;
        $data['name'] =$name;
        $data['summary'] =$summary;
        $data['periods'] =$periods;
        $data['classroom_id'] =$classroom_id;
        $data['classroom_name'] =$classroom_name;
        $data['classes_id'] =$classes_id;
        $data['classes_name'] =$classes_name;
        $data['teacher_id'] =$teacher_id;
        $data['teacher_name'] =$teacher_name;
        $data['address'] =$address;
        $data['class_time'] =$class_time;
        $data['pic'] =$pic;
        $data['isindex'] =$isindex;
        $data['ordernum'] =$ordernum;
        $data['description'] =$description;
        $data['createtime'] =time();
        $data['updatetime'] =time();
        Db::startTrans();
        try {



            // 时间从小到大排序
            $timestamp = [];
            foreach ($week_arr as $key1 => $value1) {
                $timestamp[$key1] = $value1*86400+strtotime('1970-01-01 '.$start_time_arr[$key1]);
            }
            asort($timestamp);
            $week_arr2 = $week_arr;
            $week_arr = [];
            $start_time_arr2 = $start_time_arr;
            $start_time_arr = [];
            $end_time_arr2 = $end_time_arr;
            $end_time_arr = [];
            foreach ($timestamp as $key2 => $value2) {
                $week_arr[] = $week_arr2[$key2];
                $start_time_arr[] = $start_time_arr2[$key2];
                $end_time_arr[] = $end_time_arr2[$key2];
            }




            $cdata = Db::name('course')->insertGetId($data);
            if(!$cdata) {
                Db::rollback();
                $this->res_data['Msg'] = '添加课程失败';
                return $this->res_data;
            }
            $res = $this->save_classtime($week_arr,$start_time_arr,$end_time_arr,$periods,$cdata);
            if (!$res) {
                Db::rollback();
                $this->res_data['Msg'] = '编辑课程失败';
                return $this->res_data;
            }
            Db::commit();
            $this->res_data['Msg'] = '成功';
            $this->res_data['Code'] = 0;
            return $this->printResult($this->res_data);
        } catch (\Exception $e) {
            Db::rollback();
            $this->res_data['Msg'] = "操作失败";
            return $this->res_data;
        }
	}
	public function edit($param)
	{
		$cid = isset($param['cid']) ? intval($param['cid']):0;
		$name = isset($param['name']) ? trim($param['name']):'';
		$summary = isset($param['summary']) ? trim($param['summary']):'';
        $week = isset($param['week']) ? trim($param['week']):'';
        $start_time = isset($param['start_time']) ? trim($param['start_time']):'';
        $end_time = isset($param['end_time']) ? trim($param['end_time']):'';
        $classes_id = isset($param['classes_id']) ? trim($param['classes_id']):0;
        $classroom_id = isset($param['classroom_id']) ? trim($param['classroom_id']):0;
        $periods = isset($param['periods']) ? trim($param['periods']):'';
        $address = isset($param['address']) ? trim($param['address']):'';
		$pic = isset($param['pic']) ? trim($param['pic']):'';
		$isindex = isset($param['isindex']) ? intval($param['isindex']):0;
		$ordernum = isset($param['ordernum']) ? intval($param['ordernum']):0;
		$description = isset($param['description']) ? trim($param['description']):'';
		$sid = isset($param['sid']) ? intval($param['sid']):0;
        if (!$sid || !$name || !$summary || !$week || !$start_time || !$end_time || !$classes_id || !$classroom_id || !$periods || !$address) {
          $this->res_data['Msg'] = "缺少必填信息";
          return $this->res_data;
        }
		$store= Db::name('store')->where([['id','=',$sid]])->find();
		if (!$store) {
			$this->res_data['Msg'] = "无此门店";
			return $this->res_data;
		}
		$course= Db::name('course')->where([['id','=',$cid]])->find();
		if (!$course) {
			$this->res_data['Msg'] = "无此课程";
			return $this->res_data;
		}
        $classes = Db::name('classes')->field('name,master_teacher')->where(['id'=>$classes_id])->find();
        if (!$classes) {
            $this->res_data['Msg'] = "课程班级参数有误";
            return $this->res_data;
        }
        $classes_name = $classes['name'];
        $teacher_id = $classes['master_teacher'];
        $teacher_name = Db::name('teacher')->where('id',$teacher_id)->value('name');
        $classroom_name = Db::name('classroom')->where(['id'=>$classroom_id])->value('name');
        if (!$classroom_name) {
            $this->res_data['Msg'] = "课程教室参数有误";
            return $this->res_data;
        }
        $week = trim($week,'|');
        $start_time = trim($start_time,'|');
        $end_time = trim($end_time,'|');
        $week_arr = explode('|', $week);
        $start_time_arr = explode('|', $start_time);
        $end_time_arr = explode('|', $end_time);
        if (count($end_time_arr)!=count($week_arr) || count($start_time_arr)!=count($week_arr)) {
            $this->res_data['Msg'] = "课程时间参数有误";
            return $this->res_data;
        }
        $class_time = '';
        foreach ($week_arr as $key => $value) {
            if ($key>0) {
                $class_time .= '|';
            }
            $class_time .= $value.','.$start_time_arr[$key].','.$end_time_arr[$key];
        }
        $data['name'] =$name;
        $data['summary'] =$summary;
        $data['periods'] =$periods;
        $data['classroom_id'] =$classroom_id;
        $data['classroom_name'] =$classroom_name;
        $data['classes_id'] =$classes_id;
        $data['classes_name'] =$classes_name;
        $data['teacher_id'] =$teacher_id;
        $data['teacher_name'] =$teacher_name;
        $data['address'] =$address;
        $data['class_time'] =$class_time;
        $data['pic'] =$pic;
        $data['isindex'] =$isindex;
        $data['ordernum'] =$ordernum;
        $data['description'] =$description;
    	$data['updatetime'] =time();
        Db::startTrans();
        try {



            // 时间从小到大排序
            $timestamp = [];
            foreach ($week_arr as $key1 => $value1) {
                $timestamp[$key1] = $value1*86400+strtotime('1970-01-01 '.$start_time_arr[$key1]);
            }
            asort($timestamp);
            $week_arr2 = $week_arr;
            $week_arr = [];
            $start_time_arr2 = $start_time_arr;
            $start_time_arr = [];
            $end_time_arr2 = $end_time_arr;
            $end_time_arr = [];
            foreach ($timestamp as $key2 => $value2) {
                $week_arr[] = $week_arr2[$key2];
                $start_time_arr[] = $start_time_arr2[$key2];
                $end_time_arr[] = $end_time_arr2[$key2];
            }





            $cdata = Db::name('course')->where([['id','=',$cid]])->data($data)->update();
            if(!$cdata) {
                Db::rollback();
                $this->res_data['Msg'] = '编辑失败';
                return $this->res_data;
            }
            $res = $this->save_classtime($week_arr,$start_time_arr,$end_time_arr,$periods,$cid,1);
            if (!$res) {
                Db::rollback();
                $this->res_data['Msg'] = '编辑课程失败';
                return $this->res_data;
            }
            Db::commit();
            $this->res_data['Msg'] = '成功';
            $this->res_data['Code'] = 0;
            return $this->printResult($this->res_data);
        } catch (\Exception $e) {
            Db::rollback();
            $this->res_data['Msg'] = "操作失败";
            return $this->res_data;
        }
	}

    // 课时时间详细
    // is_edit-编辑还是新建
    public function save_classtime($week_arr,$start_time_arr,$end_time_arr,$periods,$course_id,$is_edit=0)
    {
        Db::startTrans();
        try {
            // 编号数组
            $noarr = [];
            // 编辑调整课时时间时，a.已上的课不调整b.正在上的课不调整c.未开始的课调整
            // 查询未开始的课，记录课时编码，更新未开始的课时时间
            if ($is_edit) {
                $future_classtime = Db::name('classtime')->where('course_id='.$course_id.' and begin_time>'.time().' and status=1')->order('no')->select();
                if ($future_classtime){
                    $res = Db::name('classtime')->where('course_id='.$course_id.' and begin_time>'.time())->update(['status'=>0,'updatetime'=>time()]);
                    if(!$res) {
                        Db::rollback();
                        return false;
                    }
                    foreach ($future_classtime as $fc) {
                        $noarr[] = $fc['no'];
                    }
                }
            }
            $today = date('N',time());
            $classtime = [];
            $i = 0;
            if ($is_edit) $i = $noarr[0]-1;
            // foreach ($week_arr as $k => $v) {
            //     if ($v>$today) {
            //         $starttime = (($v-$today)*86400)+strtotime(date('Y-m-d').' '.$start_time_arr[$k]);
            //         $endtime = (($v-$today)*86400)+strtotime(date('Y-m-d').' '.$end_time_arr[$k]);
            //     } else {
            //         $starttime = ((7+$v-$today)*86400)+strtotime(date('Y-m-d').' '.$start_time_arr[$k]);
            //         $endtime = ((7+$v-$today)*86400)+strtotime(date('Y-m-d').' '.$end_time_arr[$k]);
            //     }
            //     for ($i=0; $i < $periods; $i++) { 
            //         $classtime[$i+$periods*$k+$k]['course_id'] = $course_id;
            //         $classtime[$i+$periods*$k+$k]['begin_time'] = $starttime+$i*7*86400;
            //         $classtime[$i+$periods*$k+$k]['end_time'] = $endtime+$i*7*86400;
            //         $classtime[$i+$periods*$k+$k]['status'] = 1;
            //         $classtime[$i+$periods*$k+$k]['createtime'] = time();
            //         $classtime[$i+$periods*$k+$k]['no'] = $i+1;
            //     }
            // }
            // 本周课程
            foreach ($week_arr as $k => $v) {
                if (!in_array($i+1, $noarr) && $is_edit==1) {
                    $i = $i+1;
                    break;
                }
                if ($v>$today) {
                    $starttime = (($v-$today)*86400)+strtotime(date('Y-m-d').' '.$start_time_arr[$k]);
                    $endtime = (($v-$today)*86400)+strtotime(date('Y-m-d').' '.$end_time_arr[$k]);
                    $classtime[$i]['course_id'] = $course_id;
                    $classtime[$i]['begin_time'] = $starttime;
                    $classtime[$i]['end_time'] = $endtime;
                    $classtime[$i]['status'] = 1;
                    $classtime[$i]['createtime'] = time();
                    $classtime[$i]['no'] = $i+1;
                    if ($noarr) {
                        $classtime[$i]['remark'] = '调整部分课时时间';
                    }
                    $i = $i+1;
                }
                if ($v==$today && $start_time_arr[$k]>time()) {
                    $starttime = (($v-$today)*86400)+strtotime(date('Y-m-d').' '.$start_time_arr[$k]);
                    $endtime = (($v-$today)*86400)+strtotime(date('Y-m-d').' '.$end_time_arr[$k]);
                    $classtime[$i]['course_id'] = $course_id;
                    $classtime[$i]['begin_time'] = $starttime;
                    $classtime[$i]['end_time'] = $endtime;
                    $classtime[$i]['status'] = 1;
                    $classtime[$i]['createtime'] = time();
                    $classtime[$i]['no'] = $i+1;
                    if ($noarr) {
                        $classtime[$i]['remark'] = '调整部分课时时间';
                    }
                    $i = $i+1;
                }
            }
            // 其余课程
            $next_monday = strtotime("next Monday");
            for ($j=0; $j < 100; $j++) { 
                foreach ($week_arr as $key => $value) {
                    if (!in_array($i+1, $noarr) && $is_edit==1) {
                        $i = $i+1;
                        break;
                    }
                    $starttime = $next_monday+($j*7*86400)+($value-1)*86400+strtotime('1970-01-01 '.$start_time_arr[$key])+8*3600;
                    $endtime = $next_monday+($j*7*86400)+($value-1)*86400+strtotime('1970-01-01 '.$end_time_arr[$key])+8*3600;
                    $classtime[$i]['course_id'] = $course_id;
                    $classtime[$i]['begin_time'] = $starttime;
                    $classtime[$i]['end_time'] = $endtime;
                    $classtime[$i]['status'] = 1;
                    $classtime[$i]['createtime'] = time();
                    $classtime[$i]['no'] = $i+1;
                    if ($noarr) {
                        $classtime[$i]['remark'] = '调整部分课时时间';
                    }
                    $i = $i+1;
                    if ($i>=$periods) {
                        break 2;
                    }
                }
            }
            if ($classtime) {
                $is_insert = Db::name('classtime')->insertAll($classtime);
                if(!$is_insert) {
                    Db::rollback();
                    return false;
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
  public function updateCourse($param)
  {
    $cid = isset($param['cid']) ? intval($param['cid']):0;
    $status = isset($param['status']) ? intval($param['status']):0;
    $course = Db::name('course')->where([['id','=',$cid]])->find();
    if (!$course) {
      $this->res_data['Msg'] = "无此课程";
      return $this->res_data;
    }
    $data['status'] =$status;
    $data['updatetime'] =time();
    $cdata = Db::name('course')->where([['id','=',$cid]])->data($data)->update();
    if(!$cdata) {
        $this->res_data['Msg'] = '更新失败';
        return $this->res_data;
    }
    $this->res_data['Msg'] = '成功';
    $this->res_data['Code'] = 0;
    return $this->printResult($this->res_data);
  }
}

?>
